package top.yongyan0624.common.exception;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/5/13
 **/

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.yongyan0624.common.lang.CodeMsg;
import top.yongyan0624.common.lang.ResultVO;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResultVO handler(AccessDeniedException e) {
        log.info("security权限不足：----------------{}", e.getMessage());
        return ResultVO.error(new CodeMsg("权限不足"));
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultVO handler(MethodArgumentNotValidException e) {
        log.info("实体校验异常：----------------{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultVO.error(new CodeMsg(objectError.getDefaultMessage()));
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResultVO handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        return ResultVO.error(new CodeMsg(e.getMessage()));
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public ResultVO handler(RuntimeException e) {
        log.error("运行时异常：----------------{}", e);
        return ResultVO.error(new CodeMsg(e.getMessage()));
    }
}
